package com.example.demo.controller.mall;

import com.example.demo.entity.Product;
import com.example.demo.entity.member.User;
import com.example.demo.service.SeckillService;
import com.example.demo.service.shop.ProductService;
import com.example.demo.util.result.Result;
import com.example.demo.util.result.ResultUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.example.demo.service.SeckillService.SECKILL_CACHE_HTML;
import static com.example.demo.service.SeckillService.SECKILL_PRODUCT_STOCK;

/**
 * Copyright (C), 2019-2019, XXX有限公司
 * FileName: SeckillController
 * Author:   longzhonghua
 * Date:     2019/4/14 14:29
 *
 * @Description: $description$
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
@Controller
@RequestMapping("seckill")
@Slf4j
public class SeckillController {
    @Resource
    private ProductService productService;
    @Resource
    private SeckillService seckillService;

    @GetMapping("/getLoginUserId")
    @ResponseBody
    public Result getLoginUserId(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if(user==null) return ResultUtil.error(500,"请先登录");
        return ResultUtil.success(200,"success",user.getId());
    }
    @ApiOperation(value = "异步从缓存中获取秒杀商品列表",produces = "application/json")
    @GetMapping(value = "/seckillListByCache",produces = "text/html")
    @ResponseBody
    public String seckillListByCache(HttpServletRequest request,
                                     HttpServletResponse response, Model model) {

        String html = seckillService.getSeckillPageFromCache();
        if(!StringUtils.isEmpty(html)) {
            return html;
        }
        //没有缓存页面，从缓存中找出秒杀商品
        List<Product> products = seckillService.getCachedProducts();
        model.addAttribute("list",products);
        //手动渲染页面并缓存
        IWebContext context = new WebContext(request,response,
                request.getServletContext(),request.getLocale(),model.asMap());
        html = seckillService.cachePage("web/shop/seckill",context);
        return html;
    }

    @ApiOperation(value = "获取秒杀商品列表，不缓存页面")
    @GetMapping("/seckillList")
    public String seckillList(Model model) {
        List<Product> productList = seckillService.getCachedProducts();
        model.addAttribute("list",productList);
        return "web/shop/seckill";
    }


    @ResponseBody
    @ApiOperation(value = "创建秒杀活动，从可销售的库存数量中预留参加秒杀活动的商品库存",
            response = Result.class,
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "商品ID",name = "productId",required = true,defaultValue = "1"),
            @ApiImplicitParam(value = "秒杀库存，小于等于可用库存",name = "stock",required = true,defaultValue = "10"),
            @ApiImplicitParam(value = "秒杀价格，小于等于商品价格",name = "stock",required = true,defaultValue = "100"),
            @ApiImplicitParam(value = "秒杀开始时间",name = "start",required = true),
            @ApiImplicitParam(value = "秒杀结束时间",name = "end",required = true)
    })
    @GetMapping("createSeckillStockCount")
    public Result createSeckill(@RequestParam("productId") Long productId,
                                @RequestParam("stock") int stock,
                                @RequestParam("price")int price,
                                @RequestParam("start")String start,
                                @RequestParam("end")String end) {
        Product product = productService.findByid(productId);
        if(product == null) {
            return ResultUtil.error(2000,"商品不存在");
        }
        if(stock>product.getStockCount()) {
            return ResultUtil.error(2001,"库存不足");
        }
        Long startTime = DateUtils.parseDate(start,new String[]{"yyyyMMddHHmmss"}).getTime();
        Long endTime = DateUtils.parseDate(end,new String[]{"yyyyMMddHHmmss"}).getTime();
        if(startTime>=endTime) {
            return ResultUtil.error(2002,"秒杀开始时间大于等小于结束时间");
        }
        //创建秒杀活动
        seckillService.createSeckill(productId,stock,price,startTime,endTime);
        return ResultUtil.success(200,"创建成功",product);
    }

    @GetMapping("seckill")
    @ResponseBody
    public Object seckill(Long userId,Long productId) {
    	Long result = seckillService.doSeckill(userId,productId);
        if (result==0) {
        	 return ResultUtil.error(500,"抢光了");
        } else if(result==-1) {
        	 return ResultUtil.error(500,"不能重复秒杀");
        } else {
            //抢购成功
        	String msg = "抢购商品"+ productId + "成功,你是第【" + result + "】個成功用戶,正在排队请稍后...";
            System.out.println(msg);
            return ResultUtil.success(200, msg, null);
        }
    }
}
